<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>定时任务 - 智能设备控制中心</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .schedule-card {
            transition: transform 0.3s, box-shadow 0.3s;
        }
        .schedule-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 16px rgba(0,0,0,0.1);
        }
        .schedule-active {
            border-left: 4px solid #198754;
        }
        .schedule-inactive {
            border-left: 4px solid #6c757d;
            opacity: 0.7;
        }
        .action-buttons {
            opacity: 0;
            transition: opacity 0.3s;
        }
        .schedule-card:hover .action-buttons {
            opacity: 1;
        }
        .cron-expression {
            font-family: monospace;
            background-color: #f8f9fa;
            padding: 2px 4px;
            border-radius: 3px;
        }
        .frequency-badge {
            font-size: 0.85rem;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm mb-4">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="fa fa-home mr-2"></i>智能设备控制中心
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ml-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/devices">设备</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/scenes">场景</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/schedules">定时任务</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/analytics">数据分析</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="row">
            <div class="col">
                <h2 class="mb-4"><i class="fa fa-clock-o text-primary"></i> 定时任务管理</h2>
                <p class="mb-4">定时任务允许您在指定时间自动执行设备操作或场景激活。点击创建按钮可以设置新的定时任务。</p>
                <button class="btn btn-primary mb-4" data-bs-toggle="modal" data-bs-target="#createScheduleModal"><i class="fa fa-plus"></i> 创建定时任务</button>
            </div>
        </div>

        <!-- 定时任务列表 -->
        <div class="row">
            {% if schedules %}
            {% for schedule in schedules %}
            <div class="col-md-6 mb-4">
                <div class="card schedule-card {{ 'schedule-active' if schedule.active else 'schedule-inactive' }}">
                    <div class="card-header d-flex justify-content-between">
                        <div>
                            <i class="fa fa-calendar mr-2"></i> {{ schedule.name }}
                        </div>
                        <div class="action-buttons">
                            <button class="btn btn-sm btn-primary mr-1" onclick="editSchedule({{ schedule.id }})"><i class="fa fa-pencil"></i></button>
                            <button class="btn btn-sm btn-danger" onclick="deleteSchedule({{ schedule.id }})"><i class="fa fa-trash"></i></button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-6">
                                <p><strong>操作类型：</strong>{{ '激活场景' if schedule.type == 'scene' else '控制设备' }}</p>
                                <p><strong>目标：</strong>{{ schedule.target_name }}</p>
                                <p><strong>状态：</strong><span class="badge {{ 'bg-success' if schedule.active else 'bg-secondary' }}">{{ '启用' if schedule.active else '禁用' }}</span></p>
                            </div>
                            <div class="col-6">
                                <p><strong>频率：</strong><span class="frequency-badge badge bg-info">{{ schedule.frequency }}</span></p>
                                <p><strong>Cron表达式：</strong><span class="cron-expression">{{ schedule.cron_expression }}</span></p>
                                <p><strong>下次执行：</strong>{{ schedule.next_run | format_datetime }}</p>
                            </div>
                        </div>
                        <div class="mt-3">
                            <button class="btn btn-sm {{ 'btn-danger' if schedule.active else 'btn-success' }} w-100" onclick="toggleSchedule({{ schedule.id }})">
                                <i class="fa {{ 'fa-pause' if schedule.active else 'fa-play' }}"></i> {{ '禁用' if schedule.active else '启用' }}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
            {% else %}
            <div class="col">
                <div class="card text-center">
                    <div class="card-body">
                        <i class="fa fa-calendar-o fa-5x text-muted mb-3"></i>
                        <h4 class="card-title">暂无定时任务</h4>
                        <p class="card-text text-muted">点击上方的"创建定时任务"按钮开始设置</p>
                    </div>
                </div>
            </div>
            {% endif %}
        </div>

        <!-- AI智能定时建议 -->
        {% if schedule_suggestions %}
        <div class="row mt-8">
            <div class="col">
                <h3 class="mb-3"><i class="fa fa-lightbulb-o text-warning"></i> AI智能定时建议</h3>
                <div class="card">
                    <div class="card-body">
                        <p class="card-text mb-4">基于您的使用习惯，我们为您推荐以下定时任务：</p>
                        <div class="list-group">
                            {% for suggestion in schedule_suggestions %}
                            <a href="#" class="list-group-item list-group-item-action" onclick="createSuggestedSchedule('{{ suggestion.name }}', '{{ suggestion.type }}', '{{ suggestion.target }}', '{{ suggestion.cron }}')">
                                <i class="fa fa-plus-circle mr-2"></i>{{ suggestion.description }}
                            </a>
                            {% endfor %}
                        </div>
                    </div>
                </div>
            </div>
        </div>
        {% endif %}
    </div>

    <!-- 创建定时任务模态框 -->
    <div class="modal fade" id="createScheduleModal" tabindex="-1" aria-labelledby="createScheduleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="createScheduleModalLabel">创建定时任务</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="createScheduleForm">
                        <div class="mb-3">
                            <label for="scheduleName" class="form-label">任务名称</label>
                            <input type="text" class="form-control" id="scheduleName" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="scheduleType" class="form-label">操作类型</label>
                            <select class="form-control" id="scheduleType" onchange="toggleScheduleTarget()">
                                <option value="device">控制设备</option>
                                <option value="scene">激活场景</option>
                            </select>
                        </div>
                        
                        <!-- 设备目标 -->
                        <div id="deviceTargetSection" class="mb-3">
                            <label for="deviceTarget" class="form-label">选择设备</label>
                            <select class="form-control" id="deviceTarget">
                                {% for device in device_config %}
                                <option value="{{ device.id }}">{{ device.name }} ({{ device.room }})</option>
                                {% endfor %}
                            </select>
                        </div>
                        
                        <div id="deviceActionSection" class="mb-3">
                            <label for="deviceAction" class="form-label">设备操作</label>
                            <select class="form-control" id="deviceAction">
                                <option value="on">开启</option>
                                <option value="off">关闭</option>
                            </select>
                        </div>
                        
                        <!-- 场景目标 (默认隐藏) -->
                        <div id="sceneTargetSection" class="mb-3" style="display: none;">
                            <label for="sceneTarget" class="form-label">选择场景</label>
                            <select class="form-control" id="sceneTarget">
                                {% for scene in scene_config %}
                                <option value="{{ scene.name }}">{{ scene.name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">执行频率</label>
                            <div class="d-flex flex-wrap gap-2">
                                <button type="button" class="btn btn-outline-primary" onclick="setCronFrequency('daily')">每天</button>
                                <button type="button" class="btn btn-outline-primary" onclick="setCronFrequency('weekly')">每周</button>
                                <button type="button" class="btn btn-outline-primary" onclick="setCronFrequency('workday')">工作日</button>
                                <button type="button" class="btn btn-outline-primary" onclick="setCronFrequency('weekend')">周末</button>
                                <button type="button" class="btn btn-outline-primary" onclick="setCronFrequency('custom')">自定义</button>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="cronExpression" class="form-label">Cron表达式</label>
                            <input type="text" class="form-control" id="cronExpression" placeholder="例如: 0 7 * * * 表示每天7点" required>
                            <small class="form-text text-muted">格式: 分 时 日 月 周 (0-6, 0=周日)</small>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-check-label">
                                <input type="checkbox" class="form-check-input" id="scheduleActive" checked>
                                创建后立即启用
                            </label>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveNewSchedule()">保存任务</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑定时任务模态框 -->
    <div class="modal fade" id="editScheduleModal" tabindex="-1" aria-labelledby="editScheduleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editScheduleModalLabel">编辑定时任务</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editScheduleForm">
                        <input type="hidden" id="editScheduleId">
                        
                        <div class="mb-3">
                            <label for="editScheduleName" class="form-label">任务名称</label>
                            <input type="text" class="form-control" id="editScheduleName" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="editScheduleType" class="form-label">操作类型</label>
                            <select class="form-control" id="editScheduleType" onchange="toggleEditScheduleTarget()">
                                <option value="device">控制设备</option>
                                <option value="scene">激活场景</option>
                            </select>
                        </div>
                        
                        <!-- 设备目标 -->
                        <div id="editDeviceTargetSection" class="mb-3">
                            <label for="editDeviceTarget" class="form-label">选择设备</label>
                            <select class="form-control" id="editDeviceTarget">
                                {% for device in device_config %}
                                <option value="{{ device.id }}">{{ device.name }} ({{ device.room }})</option>
                                {% endfor %}
                            </select>
                        </div>
                        
                        <div id="editDeviceActionSection" class="mb-3">
                            <label for="editDeviceAction" class="form-label">设备操作</label>
                            <select class="form-control" id="editDeviceAction">
                                <option value="on">开启</option>
                                <option value="off">关闭</option>
                            </select>
                        </div>
                        
                        <!-- 场景目标 (默认隐藏) -->
                        <div id="editSceneTargetSection" class="mb-3" style="display: none;">
                            <label for="editSceneTarget" class="form-label">选择场景</label>
                            <select class="form-control" id="editSceneTarget">
                                {% for scene in scene_config %}
                                <option value="{{ scene.name }}">{{ scene.name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">执行频率</label>
                            <div class="d-flex flex-wrap gap-2">
                                <button type="button" class="btn btn-outline-primary" onclick="setEditCronFrequency('daily')">每天</button>
                                <button type="button" class="btn btn-outline-primary" onclick="setEditCronFrequency('weekly')">每周</button>
                                <button type="button" class="btn btn-outline-primary" onclick="setEditCronFrequency('workday')">工作日</button>
                                <button type="button" class="btn btn-outline-primary" onclick="setEditCronFrequency('weekend')">周末</button>
                                <button type="button" class="btn btn-outline-primary" onclick="setEditCronFrequency('custom')">自定义</button>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="editCronExpression" class="form-label">Cron表达式</label>
                            <input type="text" class="form-control" id="editCronExpression" placeholder="例如: 0 7 * * * 表示每天7点" required>
                            <small class="form-text text-muted">格式: 分 时 日 月 周 (0-6, 0=周日)</small>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-check-label">
                                <input type="checkbox" class="form-check-input" id="editScheduleActive">
                                启用任务
                            </label>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updateSchedule()">更新任务</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 显示/隐藏目标类型选择
        function toggleScheduleTarget() {
            const type = document.getElementById('scheduleType').value;
            document.getElementById('deviceTargetSection').style.display = type === 'device' ? 'block' : 'none';
            document.getElementById('deviceActionSection').style.display = type === 'device' ? 'block' : 'none';
            document.getElementById('sceneTargetSection').style.display = type === 'scene' ? 'block' : 'none';
        }
        
        function toggleEditScheduleTarget() {
            const type = document.getElementById('editScheduleType').value;
            document.getElementById('editDeviceTargetSection').style.display = type === 'device' ? 'block' : 'none';
            document.getElementById('editDeviceActionSection').style.display = type === 'device' ? 'block' : 'none';
            document.getElementById('editSceneTargetSection').style.display = type === 'scene' ? 'block' : 'none';
        }
        
        // 设置Cron表达式模板
        function setCronFrequency(type) {
            const now = new Date();
            const hour = now.getHours().toString().padStart(2, '0');
            const minute = now.getMinutes().toString().padStart(2, '0');
            
            let cron = '';
            
            switch(type) {
                case 'daily':
                    cron = `${minute} ${hour} * * *`;
                    break;
                case 'weekly':
                    const dayOfWeek = now.getDay();
                    cron = `${minute} ${hour} * * ${dayOfWeek}`;
                    break;
                case 'workday':
                    cron = `${minute} ${hour} * * 1-5`;
                    break;
                case 'weekend':
                    cron = `${minute} ${hour} * * 0,6`;
                    break;
                case 'custom':
                    prompt('请输入自定义Cron表达式 (分 时 日 月 周):');
                    return;
            }
            
            document.getElementById('cronExpression').value = cron;
        }
        
        function setEditCronFrequency(type) {
            const now = new Date();
            const hour = now.getHours().toString().padStart(2, '0');
            const minute = now.getMinutes().toString().padStart(2, '0');
            
            let cron = '';
            
            switch(type) {
                case 'daily':
                    cron = `${minute} ${hour} * * *`;
                    break;
                case 'weekly':
                    const dayOfWeek = now.getDay();
                    cron = `${minute} ${hour} * * ${dayOfWeek}`;
                    break;
                case 'workday':
                    cron = `${minute} ${hour} * * 1-5`;
                    break;
                case 'weekend':
                    cron = `${minute} ${hour} * * 0,6`;
                    break;
                case 'custom':
                    prompt('请输入自定义Cron表达式 (分 时 日 月 周):');
                    return;
            }
            
            document.getElementById('editCronExpression').value = cron;
        }
        
        // 保存新任务
        function saveNewSchedule() {
            const name = document.getElementById('scheduleName').value;
            const type = document.getElementById('scheduleType').value;
            const active = document.getElementById('scheduleActive').checked;
            const cronExpression = document.getElementById('cronExpression').value;
            
            let target, action;
            if (type === 'device') {
                target = document.getElementById('deviceTarget').value;
                action = document.getElementById('deviceAction').value;
            } else {
                target = document.getElementById('sceneTarget').value;
                action = 'activate';
            }
            
            fetch('/api/create_schedule', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: name,
                    type: type,
                    target: target,
                    action: action,
                    cron_expression: cronExpression,
                    active: active
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 关闭模态框并刷新页面
                    const createModal = bootstrap.Modal.getInstance(document.getElementById('createScheduleModal'));
                    createModal.hide();
                    location.reload();
                } else {
                    alert('创建失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('创建失败');
            });
        }
        
        // 编辑任务
        function editSchedule(id) {
            // 获取任务数据
            fetch(`/api/get_schedule?id=${id}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const schedule = data.schedule;
                    
                    // 填充表单
                    document.getElementById('editScheduleId').value = id;
                    document.getElementById('editScheduleName').value = schedule.name;
                    document.getElementById('editScheduleType').value = schedule.type;
                    document.getElementById('editCronExpression').value = schedule.cron_expression;
                    document.getElementById('editScheduleActive').checked = schedule.active;
                    
                    // 设置目标选择
                    if (schedule.type === 'device') {
                        document.getElementById('editDeviceTarget').value = schedule.target;
                        document.getElementById('editDeviceAction').value = schedule.action;
                        document.getElementById('editDeviceTargetSection').style.display = 'block';
                        document.getElementById('editDeviceActionSection').style.display = 'block';
                        document.getElementById('editSceneTargetSection').style.display = 'none';
                    } else {
                        document.getElementById('editSceneTarget').value = schedule.target;
                        document.getElementById('editDeviceTargetSection').style.display = 'none';
                        document.getElementById('editDeviceActionSection').style.display = 'none';
                        document.getElementById('editSceneTargetSection').style.display = 'block';
                    }
                    
                    // 显示模态框
                    const editModal = new bootstrap.Modal(document.getElementById('editScheduleModal'));
                    editModal.show();
                } else {
                    alert('获取任务数据失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('获取任务数据失败');
            });
        }
        
        // 更新任务
        function updateSchedule() {
            const id = document.getElementById('editScheduleId').value;
            const name = document.getElementById('editScheduleName').value;
            const type = document.getElementById('editScheduleType').value;
            const active = document.getElementById('editScheduleActive').checked;
            const cronExpression = document.getElementById('editCronExpression').value;
            
            let target, action;
            if (type === 'device') {
                target = document.getElementById('editDeviceTarget').value;
                action = document.getElementById('editDeviceAction').value;
            } else {
                target = document.getElementById('editSceneTarget').value;
                action = 'activate';
            }
            
            fetch('/api/update_schedule', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    id: id,
                    name: name,
                    type: type,
                    target: target,
                    action: action,
                    cron_expression: cronExpression,
                    active: active
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 关闭模态框并刷新页面
                    const editModal = bootstrap.Modal.getInstance(document.getElementById('editScheduleModal'));
                    editModal.hide();
                    location.reload();
                } else {
                    alert('更新失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('更新失败');
            });
        }
        
        // 删除任务
        function deleteSchedule(id) {
            if (confirm('确定要删除这个定时任务吗？')) {
                fetch('/api/delete_schedule', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ id: id })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 刷新页面
                        location.reload();
                    } else {
                        alert('删除失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除失败');
                });
            }
        }
        
        // 切换任务状态
        function toggleSchedule(id) {
            fetch('/api/toggle_schedule', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ id: id })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 刷新页面
                    location.reload();
                } else {
                    alert('操作失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败');
            });
        }
        
        // 创建建议的任务
        function createSuggestedSchedule(name, type, target, cron) {
            // 填充表单
            document.getElementById('scheduleName').value = name;
            document.getElementById('scheduleType').value = type;
            document.getElementById('cronExpression').value = cron;
            document.getElementById('scheduleActive').checked = true;
            
            // 设置目标选择
            if (type === 'device') {
                document.getElementById('deviceTarget').value = target;
                document.getElementById('deviceTargetSection').style.display = 'block';
                document.getElementById('deviceActionSection').style.display = 'block';
                document.getElementById('sceneTargetSection').style.display = 'none';
            } else {
                document.getElementById('sceneTarget').value = target;
                document.getElementById('deviceTargetSection').style.display = 'none';
                document.getElementById('deviceActionSection').style.display = 'none';
                document.getElementById('sceneTargetSection').style.display = 'block';
            }
            
            // 显示模态框
            const createModal = new bootstrap.Modal(document.getElementById('createScheduleModal'));
            createModal.show();
        }
    </script>
</body>
</html>